const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const User = require('../models/User');
const Transaction = require('../models/Transaction');
const Partner = require('../models/Partner');

// 商业伙伴注册
router.post('/partners/register', async (req, res) => {
  try {
    const {
      companyName,
      businessType,
      contactPerson,
      email,
      phone,
      address,
      description
    } = req.body;

    const partner = new Partner({
      companyName,
      businessType,
      contactPerson,
      email,
      phone,
      address,
      description,
      status: 'pending'
    });

    await partner.save();
    res.status(201).json({ message: '申请已提交，我们会尽快审核' });
  } catch (error) {
    res.status(500).json({ message: '注册失败' });
  }
});

// 积分兑换
router.post('/rewards/redeem', auth, async (req, res) => {
  try {
    const { rewardId, quantity = 1 } = req.body;
    const user = await User.findById(req.userId);
    const reward = RewardSystem.rewards.find(r => r.id === rewardId);

    if (!reward) {
      return res.status(404).json({ message: '奖励项目不存在' });
    }

    const totalPoints = reward.points * quantity;
    if (user.points < totalPoints) {
      return res.status(400).json({ message: '积分不足' });
    }

    // 创建兑换记录
    const transaction = new Transaction({
      userId: req.userId,
      type: 'redeem',
      rewardId,
      quantity,
      points: totalPoints,
      status: 'pending'
    });

    // 扣除积分
    user.points -= totalPoints;
    
    await Promise.all([
      transaction.save(),
      user.save()
    ]);

    res.json({ 
      message: '兑换成功',
      remainingPoints: user.points,
      transaction: transaction._id
    });
  } catch (error) {
    res.status(500).json({ message: '兑换失败' });
  }
});

// 获取用户交易历史
router.get('/transactions', auth, async (req, res) => {
  try {
    const transactions = await Transaction.find({ userId: req.userId })
      .sort({ createdAt: -1 })
      .limit(20);
    
    res.json(transactions);
  } catch (error) {
    res.status(500).json({ message: '获取交易记录失败' });
  }
});

module.exports = router; 